// 引入vuex模块
import { createStore } from 'vuex';
import {IAdmin,ICatItem} from "@my/types";
import {ajax} from "./request";

let admin:IAdmin = {
    t_admin_pk: 0,
    admin_name: '',
    token: '',
    mobile: '',
    funList: [],
    funSet: [],
    pageURLs: []
}

let catList:ICatItem[] = [];

// 使用创建函数创建vuex对象
export default createStore({
    // state: 状态（需要在系统中用到的数据）
    state: {
        // 登录管理员
        admin,
        catList,
    },
    mutations: {
        async setAdmin(state, payload:IAdmin) {
            let pageURLs:string[] = [];
            if (payload.funList) {
                payload.funList.forEach((v:any) => {
                    v.subList.forEach((v:any) => {
                        if (v) {
                            pageURLs.push(v.page_url);
                        }
                    })
                })
                payload.pageURLs = pageURLs;
            }
            state.admin = payload;
            // 如果是清空admin，那么也清空catList
            if (Object.keys(payload).length == 0) {
                state.catList = [];
                return;
            }
            try {
                let res = await ajax("/cat/queryList");
                if (res.data.status > 0) {
                    state.catList = res.data.result_data;
                } else {
                    state.catList = [];    
                }
            } catch {
                state.catList = [];
            }
        },
    },
    getters: {
        hasFun: state => (url:string) => state.admin.funSet ? state.admin.funSet.some(v => v == url) : false,
    },
});